package com.example.demo.music;

import cn.hutool.core.lang.UUID;
import com.iflytek.cloud.speech.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/*
 *
 *   @Author: Sjy
 *   @Date: 2024/4/10-04-10-11:27
 *   用于语音合成生成对应的音频，返回地址给前端播放
 */
@Slf4j
@Component
public class TtsMusicUtil {

    private static SpeechSynthesizer mTts;

    static {
        SpeechUtility.createUtility( SpeechConstant.APPID +"=90a1e314");
        mTts = SpeechSynthesizer.createSynthesizer();
        //音色
        mTts.setParameter(SpeechConstant.VOICE_NAME,"x_xiaoxin");
        //语速
        mTts.setParameter(SpeechConstant.SPEED,"50");
        //音量
        mTts.setParameter(SpeechConstant.VOLUME,"100");
        //音频保存格式
        mTts.setParameter(SpeechConstant.AUDIO_FORMAT,"wav");
        //设置云端
        mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);

    }

    // 发送HTTP请求进行语音合成，并获取音频的URL
    public String syntheticAudio(String message) {
        //Hutool uuid文件名生成
        String uuid = UUID.randomUUID().toString();
        //播放类型 SpeechConstant.STREAM_TYPE
        mTts.setParameter(SpeechConstant.STREAM_TYPE, "3");
        //音频保存位置
        mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, "C:/111/"+uuid+".wav");
        mTts.startSpeaking(message.trim(), mSynListener);
        //生成虚拟路径地址
        return "/player_music/"+uuid+".wav";
    }

    // 音频监听器
    private SynthesizerListener mSynListener = new SynthesizerListener() {
        @Override
        public void onSpeakBegin() {}
        @Override
        public void onBufferProgress(int progress, int beginPos, int endPos, String info) {}
        @Override
        public void onSpeakPaused() {}
        @Override
        public void onSpeakResumed() {}
        @Override
        public void onSpeakProgress(int progress, int beginPos, int endPos) {}
        @Override
        public void onCompleted(SpeechError error) {}
        @Override
        public void onEvent(int i, int i1, int i2, int i3, Object o, Object o1) {}
    };
}